csrc = $(wildcard src/*.c)
ccsrc = $(wildcard src/*.cc)
obj = $(csrc:.c=.o) $(ccsrc:.cc=.o)
depfiles = $(obj:.o=.d)

abi_major = 3
abi_minor = 1

lib_a = libvmath.a

ifeq ($(shell uname -s), Darwin)
	lib_so = libvmath.dylib
	shared = -dynamiclib
else
	solink = libvmath.so
	soname = $(solink).$(abi_major)
	lib_so = $(soname).$(abi_minor)
	shared = -shared -Wl,-soname,$(soname)
	pic = -fPIC
endif

CFLAGS = -std=c89 -pedantic -Wall -Wno-strict-aliasing $(opt) $(dbg) $(pic) -Isrc
CXXFLAGS = -ansi -pedantic -Wall -Wno-strict-aliasing $(opt) $(dbg) $(pic) -Isrc
LDFLAGS = -lm

.PHONY: all
all: $(lib_a) $(lib_so)

$(lib_a): $(obj)
	$(AR) rcs $@ $(obj)

$(lib_so): $(obj)
	$(CXX) $(CFLAGS) $(shared) -o $@ $(obj) $(LDFLAGS)

.PHONY: install
install: $(lib_a) $(lib_so)
	@echo "lib_so: $(lib_so)"
	@echo "soname: $(soname)"
	@echo "solink: $(solink)"
	mkdir -p $(DESTDIR)$(PREFIX)/include/vmath $(DESTDIR)$(PREFIX)/lib
	cp src/*.h src/*.inl $(DESTDIR)$(PREFIX)/include/vmath/
	cp $(lib_a) $(DESTDIR)$(PREFIX)/lib/$(lib_a)
	cp $(lib_so) $(DESTDIR)$(PREFIX)/lib/$(lib_so)
	[ -n "$(solink)" ] \
		&& cd $(DESTDIR)$(PREFIX)/lib \
		&& rm -f $(solink) $(soname) \
		&& ln -s $(lib_so) $(soname) \
		&& ln -s $(soname) $(solink) \
		|| true
	mkdir -p $(DESTDIR)$(PREFIX)/lib/pkgconfig
	cp vmath.pc $(PREFIX)/lib/pkgconfig/vmath.pc

.PHONY: uninstall
uninstall:
	rm -f $(DESTDIR)$(PREFIX)/include/vmath/*
	rmdir $(DESTDIR)$(PREFIX)/include/vmath
	rm -f $(DESTDIR)$(PREFIX)/lib/$(lib_a)
	rm -f $(DESTDIR)$(PREFIX)/lib/$(lib_so)
	[ -n "$(solink)" ] \
		&& rm -f $(DESTDIR)$(PREFIX)/lib/$(solink) \
		&& rm -f $(DESTDIR)$(PREFIX)/lib/$(soname) \
		|| true
	rm -f $(DESTDIR)$(PREFIX)/lib/pkgconfig/vmath.pc

-include $(depfiles)

%.d: %.c
	@$(CPP) $(CFLAGS) $< -MM -MT $(@:.d=.o) >$@

%.d: %.cc
	@$(CPP) $(CXXFLAGS) $< -MM -MT $(@:.d=.o) >$@


.PHONY: clean
clean:
	rm -f $(obj) $(depfiles)

.PHONY: distclean
distclean:
	rm -f $(obj) $(depfiles) $(lib_so) $(lib_a) Makefile vmath.pc
